import type { FC } from "react";
import { useMemo } from "react";
import { Breadcrumb } from 'antd';
import { useLoaderData ,useLocation} from "react-router-dom";

type BreadcrumbItem = {
    title: string;
};

const RootBreadcrumb: FC = () => {
    const loaderData = useLoaderData() as { menus: MenuItem[] } | null;
    const location = useLocation();
    const nowPath = location.pathname === '/' ? '/home' : location.pathname;

    //好像到react19就不用这么写了
    const items = useMemo(()=>resolveBreadcrumbItems(loaderData?.menus, nowPath),[loaderData,nowPath])

    return <Breadcrumb items={items} />;
};

// 定义一个递归的函数，递归生成面包屑导航的数据源
const resolveBreadcrumbItems = (
    menus: MenuItem[] | undefined,
    nowPath: string,
    breadcrumbItems: BreadcrumbItem[] = []
): BreadcrumbItem[] | undefined => {
    if (!menus) return undefined; // 处理 menus 为 undefined 的情况

    for (const item of menus) {
        if (item.key === nowPath) {
            // 找到了路径，返回当前项和之前的 breadcrumbItems 数组
            return [...breadcrumbItems, { title: item.label }];
        }
        if (item.children) {
            // 递归查找子节点
            const result = resolveBreadcrumbItems(item.children, nowPath, [...breadcrumbItems, { title: item.label }]);
            if (result) {
                // 找到了子节点的路径，直接返回结果，不再修改 breadcrumbItems
                return result;
            }
        }
    }
    
    // 如果遍历完毕仍未找到路径，返回 undefined 或者空数组，视需求而定
    return undefined; // 或者 return [];
};

export default RootBreadcrumb